package com.webware.view.client.admin.view;

import java.util.ArrayList;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.Timer;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.Range;
import com.google.gwt.view.client.TreeViewModel;
import com.webware.view.shared.BaseFolder;
import com.webware.view.shared.Folder;

public class FolderTreeModel implements TreeViewModel {
    public class FolderDataProvider extends AsyncDataProvider<Folder> {
	protected void onRangeChanged(final HasData<Folder> display) {
	    //show loader
	    updateRowCount(1, true);

	    Timer timer = new Timer() {
		@Override
		public void run() {
		    ArrayList<Folder> list = new ArrayList<Folder>();
		    for (int i = 0; i < 2; i++) {
			list.add(new BaseFolder("Folder" + "."
				+ String.valueOf(i)));
		    }

		    Range range = display.getVisibleRange();
		    int start = range.getStart();
		    updateRowData(start, list);
		}
	    };
	    timer.schedule(1000);
	}
    }

    private ArrayList<Folder> folders = new ArrayList<Folder>();

    @Override
    public <T> NodeInfo<?> getNodeInfo(T value) {
	if (value == null) {
	    // LEVEL 0.
	    ListDataProvider<Folder> dataProvider = new ListDataProvider<Folder>(
		    folders);

	    Cell<Folder> cell = new AbstractCell<Folder>() {
		@Override
		public void render(
			com.google.gwt.cell.client.Cell.Context context,
			Folder value, SafeHtmlBuilder sb) {
		    if (value != null) {
			sb.appendEscaped(value.getName());
		    }
		}
	    };
	    return new DefaultNodeInfo<Folder>(dataProvider, cell);
	} else if (value instanceof Folder) {
	    // LEVEL 1.
	    ListDataProvider<Folder> dataProvider = new ListDataProvider<Folder>(
		    ((Folder) value).getChilds());
	    Cell<Folder> cell = new AbstractCell<Folder>() {
		@Override
		public void render(Context context, Folder value,
			SafeHtmlBuilder sb) {
		    if (value != null) {
			sb.appendEscaped(value.getName());
		    }
		}
	    };
	    // return new DefaultNodeInfo<Folder>(dataProvider, cell);
	    return new DefaultNodeInfo<Folder>(new FolderDataProvider(), cell);
	}
	return null;
    }

    @Override
    public boolean isLeaf(Object value) {
	return (value instanceof Folder)
		&& (((Folder) value).getChilds().size() > 0);
    }

    public ArrayList<Folder> getFolders() {
	return folders;
    }

    public void setFolders(ArrayList<Folder> folders) {
	this.folders.clear();
	if (folders != null)
	    this.folders.addAll(folders);
    }
}
